package tasks.leetcode;

import java.util.Arrays;

public class TaskIntersect2 {
    public static void main(String[] args) {
        int[] intersect = new TaskIntersect2().intersect(new int[]{1, 2, 2, 1}, new int[]{2, 2});
        System.out.println(intersect);
    }

    public int[] intersect(int[] nums1, int[] nums2) {
        Arrays.sort(nums1);
        Arrays.sort(nums2);

        int length1 = nums1.length;
        int length2 = nums2.length;
        int minLength = Math.min(length1, length2);
        int[] array = new int[minLength];
        int index = 0, leftIndex = 0, rightIndex = 0;
        while (leftIndex < length1 && rightIndex < length2) {
            if (nums1[leftIndex] < nums2[rightIndex]) {
                leftIndex++;
            } else if (nums1[leftIndex] > nums2[rightIndex]) {
                rightIndex++;
            } else {
                // 相等的场景
                array[index++] = nums1[leftIndex];
                leftIndex++;
                rightIndex++;
            }
        }

        return Arrays.copyOfRange(array, 0, index);
    }
}